package com.digital.smartgrow.common.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.digital.smartgrow.common.exception.TokenException;
import com.digital.smartgrow.entity.datacenter.Teacher;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebTool {

    private static Cache<String, Teacher> teacherCache;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public WebTool(Cache<String, Teacher> teacherCache) {
        this.teacherCache = teacherCache;
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
            if (StringUtils.isBlank(token)) {
                token = (String) request.getAttribute("token");
                if (StringUtils.isBlank(token)) {
                    throw new TokenException("token不能为空");
                }
            }
        }
        return token;
    }

    public static Teacher getCurrentUser() {
        HttpServletRequest request = WebTool.getRequest();
        String token = WebTool.getToken(request);
        Teacher teacher = teacherCache.getIfPresent(token);
        if (teacher == null) {
            throw new TokenException("用户没有登录或者token已经失效");
        }
        return teacher;
    }
}
